import styles from './index.module.less';

import { useEffect, useState } from 'react';
import { Preview } from '@lle/d3-preview';
import { IPartInfo } from '@/types';
import { getPart } from '@/api/parts';
import { PartInfo } from '../PartInfo';

interface IProps {
  preview: Preview;
}

export const PartsInfo = (props: IProps) => {
  const { preview } = props;
  const [panelInfos, setPanelInfos] = useState<IPartInfo[]>([]);

  const fetchPart = async (foNo: string) => {
    const response = await getPart(foNo);

    return response.data;
  };

  useEffect(() => {
    const onParClick = async (foNos: string[]) => {
      const promises = [];

      for (let i = 0; i < foNos.length; i++) {
        const element = foNos[i];
        promises.push(fetchPart(element));
      }

      const results = await Promise.all(promises);

      setPanelInfos(results);
    };
    preview.bus.on('PARTS_SHOW', onParClick);
    return () => {
      preview.bus.off('PARTS_SHOW', onParClick);
    };
  }, [preview]);

  useEffect(() => {
    const onPartsHide = () => {
      setPanelInfos([]);
    };
    preview.bus.on('PARTS_HIDE', onPartsHide);

    return () => {
      preview.bus.off('PARTS_HIDE', onPartsHide);
    };
  }, [preview]);

  useEffect(() => {
    const onPartsClick = async (foNo: string) => {
      const foNos = [foNo];
      const promises = [];

      for (let i = 0; i < foNos.length; i++) {
        const element = foNos[i];
        promises.push(fetchPart(element));
      }

      const results = await Promise.all(promises);

      setPanelInfos(results);
    };
    preview.bus.on('PART_CLICK', onPartsClick);

    return () => {
      preview.bus.off('PART_CLICK', onPartsClick);
    };
  }, [preview]);

  return (
    <div className={styles.container}>
      {panelInfos.map(item => (
        <PartInfo key={item.foNo} panelInfo={item} />
      ))}
    </div>
  );
};
